package com.himalayan.bear.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.himalayan.bear.entity.User;
import com.himalayan.bear.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author zjk
 * @since 2019-04-25
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    protected UserService userService;

    @PostMapping("/login")
    public String login(User user, String verify, Model model, HttpSession session) {
        if (user == null) {
            model.addAttribute("message", "登录方法异常！");
            return "page/login/login";
        }
        if (StringUtils.isEmpty(user.getUsername()) || StringUtils.isEmpty(user.getPassword())) {
            model.addAttribute("message", "用户名和密码不能为空！");
            return "page/login/login";
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>()
                .eq("enable_flag", 1)
                .eq("delete_flag", 0)
                .eq("username", user.getUsername())
                .eq("password", user.getPassword());
        User orgUser = userService.getOne(queryWrapper, true);
        if (orgUser != null) {
            session.setAttribute("currentUser", orgUser);
            return "redirect:/index";
        }
        model.addAttribute("user", user);
        model.addAttribute("validCode", verify);
        model.addAttribute("message", "用户名或密码可能不正确！");
        return "page/login/login";
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("currentUser");
        return "page/login/login";
    }
}
